﻿using AutoMapper;
using General.Core.Data;
using General.Entities.Data;
using General.Entities.Models;
using General.Entities.ViewData.Department;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace General.Services.Department
{
    public class DepartmentService : IDepartmentService
    {
        private readonly IRepository<tc_department> tc_DepartmentRepository;
        private readonly IRepository<tc_departmentaccount> tc_DepartmentaccountRepository;
        private readonly IMapper mapper;

        public DepartmentService(IRepository<tc_department> tc_departmentRepository,
            IRepository<tc_departmentaccount> tc_departmentaccountRepository,
            IMapper mapper)
        {
            tc_DepartmentRepository = tc_departmentRepository;
            tc_DepartmentaccountRepository = tc_departmentaccountRepository;
            this.mapper = mapper;
        }

        /// <summary>
        /// 获取列表信息    
        /// </summary>
        /// <returns></returns>
        public async Task<AdminResult> GetList()
        {
            AdminResult result = new AdminResult();
            var res = await tc_DepartmentRepository.GetAllAsync().OrderBy(x=>x.seq).ToListAsync();
            var data = mapper.Map<List<DepartmentModel>>(res);
            result.count = data.Count();
            result.data = data;
            result.code = 0;
            return result;
        }


        /// <summary>
        /// 根据id查询
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<tc_department> GetDataByID(int id)
        {
            var data = await tc_DepartmentRepository.GetAsync(x => x.id == id);
            return data;
        }


        /// <summary>
        /// 添加机构数据
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task AddInfo(DepartmentModel model,int uid)
        {
            tc_department data = new tc_department();
            data.createTime = DateTime.Now;
            data.cuser_id = uid;
            if (model.select == null)
            {
                data.level = "0";
                data.parent_id = 0;
            }
            else
            {
                var parentRes = await GetDataByID(Convert.ToInt32(model.select));
                data.level = parentRes.level + "." + parentRes.id;

                data.parent_id = Convert.ToInt32(model.select);
            }
            data.muser_id = uid;
            data.name = model.organizationName;
            data.organizationType = Convert.ToInt32(model.organizationType);
            data.seq = Convert.ToInt32(model.sortNumber);
            data.updateTime = DateTime.Now;

            await tc_DepartmentRepository.insertAsync(data);
        }

        /// <summary>
        /// 编辑机构数据
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<int> EditInfo(DepartmentModel model, int uid)
        {
            tc_department data = new tc_department();
            data.id = Convert.ToInt32(model.organizationId);
            data.createTime = DateTime.Now;
            data.muser_id = uid;
            if (model.select == null)
            {
                data.level = "0";
                data.parent_id = 0;
            }
            else
            {
                var parentRes = await GetDataByID(Convert.ToInt32(model.select));
                data.level = parentRes.level + "." + parentRes.id;

                data.parent_id = Convert.ToInt32(model.select);
            }
            data.name = model.organizationName;
            data.organizationType = Convert.ToInt32(model.organizationType);
            data.seq = Convert.ToInt32(model.sortNumber);
            data.updateTime = DateTime.Now;

            Expression<Func<tc_department, object>>[] updatedProperties = {
                    p => p.updateTime,p=>p.level,p=>p.muser_id,p=>p.name,p=>p.organizationType,
                    p=>p.parent_id,p=>p.seq,
                };
            return await tc_DepartmentRepository.UpdateByFieldsAsync(data, updatedProperties);
        }


        /// <summary>
        /// 删除机构数据
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<int> DeleteInfo(int id)
        {
            var model = await tc_DepartmentRepository.getByIdAsync(id);
            var res1 = await tc_DepartmentRepository.DeleteAsync(model);
            var list = await tc_DepartmentRepository.Table.Where(x=>x.level.StartsWith(model.level+"."+id.ToString())).ToListAsync();
            //删除部门下的成员
            List<int> deleteDeparmentIds = new();
            deleteDeparmentIds.Add(id);
            foreach (var item in list)
            {
                deleteDeparmentIds.Add(item.id);
            }
            var daList = await tc_DepartmentaccountRepository.Table.Where(x => deleteDeparmentIds.Contains(x.departmentId)).ToListAsync();
            await tc_DepartmentaccountRepository.DeleteListAsync(daList);

            var res2 = await tc_DepartmentRepository.DeleteListAsync(list);
            return res1 + res2;
        }

        /// <summary>
        /// 将用户添加到机构
        /// </summary>
        /// <param name="did"></param>
        /// <param name="uid"></param>
        /// <returns></returns>
        public async Task AddAccountDepartment(int did, string uid,int cuserId)
        {
            var uidArr = uid.Split(",", StringSplitOptions.RemoveEmptyEntries);
            List<tc_departmentaccount> list = new List<tc_departmentaccount>();
            foreach (var item in uidArr)
            {
                list.Add(new tc_departmentaccount() { 
                     uid = Convert.ToInt32(item), createTime = DateTime.Now, cuser_id = cuserId, departmentId = did
                });
            }
            await tc_DepartmentaccountRepository.AddListAsync(list);
        }

        /// <summary>
        /// 是否账号已存在此部门
        /// </summary>
        /// <param name="did"></param>
        /// <param name="uid"></param>
        /// <returns></returns>
        public async Task<bool> IsExistAccountDepartment(int did, string uid)
        {
            var uidArr = uid.Split(",", StringSplitOptions.RemoveEmptyEntries).Select<string, int>(x => Convert.ToInt32(x));
            return await tc_DepartmentaccountRepository.IsExistAsync(x=>x.departmentId == did && uidArr.Contains(x.uid));
        }

        /// <summary>
        /// 批量删除部门所在的用户
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<int> DeleteAccountDepartment(string ids)
        {
            var arr = ids.Split(",", StringSplitOptions.RemoveEmptyEntries);
            List<tc_departmentaccount> list = new List<tc_departmentaccount>();
            foreach (var item in arr)
            {
                list.Add(new tc_departmentaccount() { id = Convert.ToInt32(item) });
            }

            return await tc_DepartmentaccountRepository.DeleteListByFieldsAsync(list);
        }
    }
}
